package com.lge.clock.worldclock;

import java.io.IOException;
import java.util.ArrayList;

import com.lge.clock.AlarmClockActivity;
import com.lge.clock.R;
import com.lge.clock.WorldClockFragment;
import com.lge.clock.worldclock.cities.CityDBManager;
import com.lge.clock.worldclock.cities.CityInformation;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author lge.com
 */
public class DeleteListActivity extends Activity implements OnClickListener {
	
	static final String TAG = "DeleteListActivity";
	
    private static final int DIALOG_DELETE = 2;
	
    private ArrayList<CityInformation> registCityArray = null;
    private ArrayList<CityInformation> deleteCityArray = null;
    
    private Button	deleteButton = null;
    private Button	cancelButton = null;
    private ListView deleteListView = null;
    private CheckedTextView mCheckAll = null; 		// 2011 02 09 - Linkgenesis - dhong.kim@lge.com : Titel CheckBox Click Event
    private TextView mDeleteCount = null;
    private TextView selectAllText = null;
    
    private WorldClockAdapter mWCAdapter = null;
    private TheBroadcastReceiver intentReceiver;
    private CityDBManager mCityManager = null;
	
    private int delete_msg = -1;
    private int delete_title = -1;
    private AlertDialog.Builder mDeleteDialog;
    
   
    private String mTrue = "true";
    private String mFalse = "false";
    
    private String mFromWidget = null;
      
    
	/**
	 * Method onCreate.
	 */
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		
        super.onCreate(savedInstanceState);        
        Log.d(TAG, "onCreate");
        //added by essin@lge.com 2011.01.07 check box title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        Intent intent = getIntent();
        mFromWidget = intent.getStringExtra("from");        
       
        // initialize city info data
        try {
			mCityManager = CityDBManager.getInstance(this);
		} catch (IOException e) {
			e.printStackTrace();
		}		
        initReceiver();
        
        setContentView(R.layout.worldclock_delete_city_list);
        
        // BEGIN - 2011 02 09 - Linkgenesis - dhong.kim@lge.com : Titel CheckBox Click Event
        
        mCheckAll = (CheckedTextView) findViewById(R.id.checkall);
        mCheckAll.setChecked(false);
        mCheckAll.setOnClickListener(this);
        // END - 2011 02 09 - Linkgenesis - dhong.kim@lge.com : Titel CheckBox Click Event

        deleteCityArray = new ArrayList<CityInformation>();
        registCityArray = mCityManager.getWorldClockList(this);

        mWCAdapter = new WorldClockAdapter(this, R.layout.worldclock_delete_city_list_item, registCityArray, mFromWidget);

        deleteListView = (ListView)findViewById(R.id.list_delete);
        deleteListView.setAdapter(mWCAdapter);
        deleteListView.setOnItemClickListener(new OnItemClickListener() {	
        	public void onItemClick(AdapterView<?> arg0, View arg1, int index,long arg3) {
        		CityInformation item;
        		
        		item = mWCAdapter.getItem(index);
        		item.toggleCheckedStatus();        		
        		mWCAdapter.notifyDataSetChanged();
        		
        		// Store/remove the item in deleteList  
        		if(item.getChecked() == true) {
        		    deleteCityArray.add(item);
        		} else {
        		    deleteCityArray.remove(item);
        		}
        		
        		if(deleteCityArray.size() > 0)
        			deleteButton.setEnabled(true);
        		else
        			deleteButton.setEnabled(false);
        		//added by essin@lge.com 2011.01.07
        		if(deleteCityArray.size() == deleteListView.getCount())
        		{
        			mCheckAll.setChecked(true);
        		}
        		else
        		{
        			mCheckAll.setChecked(false);
        		}
        		
        		setSelectedItem();
			}
		});
        
        deleteButton = (Button)findViewById(R.id.btn_Delete);
        deleteButton.setOnClickListener(this);
        deleteButton.setEnabled(false);
        cancelButton = (Button)findViewById(R.id.alert_dialog_cancel);
        cancelButton.setOnClickListener(this);
		
		selectAllText = (TextView) findViewById(R.id.DeleteTitleString);
		selectAllText.setOnClickListener(this);
	}
	
	private void initReceiver() {
        intentReceiver = new TheBroadcastReceiver();
        IntentFilter filter = new IntentFilter(); 
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        if(intentReceiver != null) {
        registerReceiver(intentReceiver, filter);   
        }
    }
	
	

    @Override
	protected void onPause() {
    	Log.d(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		Log.d(TAG, "onRestart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//[suhaeng.lee][6293] 2012.04.11 START
		if(mWCAdapter.getCount() == 0){
			Intent intent = new Intent(DeleteListActivity.this, AlarmClockActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
			startActivity(intent);
			finish();
		}
		//[suhaeng.lee][6293] 2012.04.11 END
		
		setSelectedItem();
		refreshTime();
	}
	
	@Override
	protected void onStart() {
		Log.d(TAG, "onStart");
		super.onStart();
	}


	@Override
	protected void onStop() {
		Log.d(TAG, "onStop");
		super.onStop();
	}

	/**
     * Method onDestroy.
     */
    @Override
    protected void onDestroy() {
    	Log.e(TAG, "onDestroy");
    	
    	if(intentReceiver != null) {
	    	try{
	    		unregisterReceiver(intentReceiver);
	    	}catch(Exception e){
				e.printStackTrace();
			}
    	}
    	super.onDestroy(); 
    }
    
    private void moveToClock() {
		Intent intent = new Intent(DeleteListActivity.this, WorldClockFragment.class);
    	setResult(RESULT_OK, intent);
        finish();
    }

	/**
	 * Method onClick.
	 */
	public void onClick(View v) {
		if(v.equals(deleteButton))
		{	
			if( deleteCityArray.size() > 0 ) {
				Log.i("DeleteListActivity", "deleteCityArray.size() : " + deleteCityArray.size());
				Log.i("DeleteListActivity", "registCityArray.size() : " + registCityArray.size());
				
				setDeleteString();
				if(mDeleteDialog != null)
					removeDialog(DIALOG_DELETE);
				showDialog(DIALOG_DELETE);
			} else {
				Toast.makeText(this, R.string.msg_non_city_list, Toast.LENGTH_SHORT).show();
			}
		}
		else if(v.equals(cancelButton))
		{
	        finish();
		}
		else if(v.equals(selectAllText))
		{
			CityInformation item;
			//WBT fix td 207889
			if (mCheckAll != null)
			{
				if (mCheckAll.isChecked())
				{
					for (int i = 0; i < deleteListView.getCount(); i++) {
						item = mWCAdapter.getItem(i);
                		if(item.getChecked() == true)
                		{
                			item.setChecked(false);
                			deleteCityArray.remove(item);
                		}
					}
					deleteButton.setEnabled(false);
					mCheckAll.setChecked(false);
				}
				else
				{
					for (int i = 0; i < deleteListView.getCount(); i++) {
						item = mWCAdapter.getItem(i);
                    	if(item.getChecked() == false)
                    	{
                    		item.setChecked(true);
                    		deleteCityArray.add(item);
                    	}
					}
					deleteButton.setEnabled(true);
					mCheckAll.setChecked(true);
				}
			}
			
			
			setSelectedItem();
            mWCAdapter.notifyDataSetChanged();
		}
		// BEGIN - 2011 02 09 - Linkgenesis - dhong.kim@lge.com : Titel CheckBox Click Event
		else if(v.equals(mCheckAll))
		{
			CheckedTextView checkAll = (CheckedTextView) findViewById(R.id.checkall);
			
			CityInformation item;
			//WBT fix td 207890
			if (checkAll != null)
			{
				if (checkAll.isChecked() == false)
				{
					for (int i = 0; i < deleteListView.getCount(); i++) {
						item = mWCAdapter.getItem(i);
                		if(item.getChecked() == false)
                		{
                			item.setChecked(true);
                			deleteCityArray.add(item);
                		}
					}
					deleteButton.setEnabled(true);
					checkAll.setChecked(true);
				}
				else
				{
					for (int i = 0; i < deleteListView.getCount(); i++) {
						item = mWCAdapter.getItem(i);
                    	if(item.getChecked() == true)
                    	{
                    		item.setChecked(false);
                    		deleteCityArray.remove(item);
                    	}
					}
					deleteButton.setEnabled(false);
					checkAll.setChecked(false);
				
				}
			}
			
			setSelectedItem();
            mWCAdapter.notifyDataSetChanged();
		}
		// END - 2011 02 09 - Linkgenesis - dhong.kim@lge.com : Titel CheckBox Click Event
		
	}

	private long getSystemOffset() {
        Time today = new Time();
        today.setToNow();
        return (long)(today.gmtoff* 1000);
    }
	
    private void refreshTime() {
        long systemOffset = getSystemOffset();
        
        // refresh list
        mWCAdapter.setSystemOffset(systemOffset);
        mWCAdapter.notifyDataSetChanged();
    }
	
	/**
	 * Method onKeyDown.
	 * @see android.view.KeyEvent$Callback#onKeyDown(int, KeyEvent) */
	@Override 
	public boolean onKeyDown (int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK) {
	        finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * Method onCreateDialog.
	 */
	@Override 
	protected Dialog onCreateDialog(int id) {
        switch (id) {
            case (DIALOG_DELETE) : {
            	setDeleteString();
            	mDeleteDialog = new AlertDialog.Builder(this);
        		return mDeleteDialog.setTitle(delete_title)
//        		.setIcon(android.R.drawable.ic_dialog_alert)
        		.setIconAttribute(android.R.attr.alertDialogIcon)
        		.setMessage(delete_msg)
    	    	.setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int which) {
    				    mCityManager.deleteSelectedCity(deleteCityArray);
    				    Toast.makeText(DeleteListActivity.this, getString(R.string.delete_toast), Toast.LENGTH_SHORT).show();
    				    moveToClock();
    				}
    			})
    	    	.setNegativeButton(R.string.alert_dialog_cancel,null)
        		.create();
        	}
            default :
        }
        return null;
    }
	
    /**
     * @author hyeongjoo.park
     */
    public class TheBroadcastReceiver extends BroadcastReceiver { 
        /**
         * Method onReceive.
         */
        public void onReceive(Context context, Intent intent) {
            Log.d("FROCS","Time Tick occured the event@@@2222");
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                Log.d("FROCS","Time Tick occured the event!!!!");
                refreshTime();
            }else if(intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
                Log.d("FROCS","TIMEZONE_CHANGED occured the event!!!!");
                refreshTime();
            }
        }
    }
    
    private void setDeleteString() {
    	//[mo2sangbong.lee][1832] 2011.11.14 START
		if(deleteCityArray.size() == registCityArray.size()){
			delete_msg = R.string.all_delete_message;
			delete_title = R.string.menu_deleteall;
		}
		else if (deleteCityArray.size() == 1){
			delete_msg = R.string.sp_THISCITY_NORMAL;
			delete_title = R.string.menu_multiselect;
		} else {
			delete_msg = R.string.some_delete_message;
			delete_title = R.string.menu_multiselect;
		}
		//[mo2sangbong.lee][1832] 2011.11.14 END
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		ArrayList<String> checkedItemPositions;
		super.onSaveInstanceState(outState);
		if(registCityArray.size()> 0){
			String mCheck = null;
			checkedItemPositions = new ArrayList<String>();
			for(int i=0;i< registCityArray.size();i++){
        		if(mWCAdapter.getItem(i).getChecked() == true){
        			mCheck = mTrue;
        		}else{
        			mCheck = mFalse;
        		}
        		checkedItemPositions.add(mCheck);
			}
        	outState.putStringArrayList("CheckedItem", checkedItemPositions);
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		ArrayList<String> checkedItemPositions;
		
		super.onRestoreInstanceState(savedInstanceState);
		checkedItemPositions = savedInstanceState.getStringArrayList("CheckedItem");
		    	  
		//haesun.jung@lge.com [WBT_12][E610][41767] 2012.01.17 
    	if(checkedItemPositions != null) {
    		try{
	    		CityInformation item;  
		    	for(int i=0;i<checkedItemPositions.size();i++){
		    		item = mWCAdapter.getItem(i);
		    		if(checkedItemPositions.get(i).equals(mTrue)){    			
		    			item.setChecked(true);
		    			deleteCityArray.add(item);
		    		}else{
		    			item.setChecked(false);
		    		}
		    		mWCAdapter.notifyDataSetChanged();
		    	}
    		}catch(Exception e){
    			Log.e(TAG, "Exception => onRestoreInstanceState : "+e.getMessage());
    		}
    	}
    	
    	if(deleteCityArray.size()== registCityArray.size()){
    		CheckedTextView checkAll = (CheckedTextView) findViewById(R.id.checkall);
    		checkAll.setChecked(true);
    	}
    	//deleteButton.setEnabled(true);
    	if(deleteCityArray.size() > 0)
			deleteButton.setEnabled(true);
		else
			deleteButton.setEnabled(false);
    	
	}
	
	private void setSelectedItem(){
		
		int count = deleteCityArray != null ? deleteCityArray.size() : 0;
		
		mDeleteCount = (TextView)findViewById(R.id.SelectedItem);
		if(mDeleteCount != null )
			mDeleteCount.setText(String.format(getString(R.string.sp_selected_NORMAL),	count));
	} 
    
}
